package c_gw

import (
	"cade/src/gate/app"
	"cade/src/gate/app/dbmgr"
	"cade/src/gate/msg"
	Err "cade/src/proto/errorcode"
)

func C_Login(message msg.Message, ctx interface{}) {
	// !Note: in net-thread

	req := message.(*msg.C_Login)
	sess := ctx.(*app.Session)

	ec := func() int32 {
		// 开始登录
		if !sess.LoginBegin() {
			return Err.Login_Failed
		}

		// 延后结束登录
		defer sess.LoginEnd()

		// authenticated ?
		if !sess.IsAuthenticated() {
			return Err.Login_Failed
		}

		// get user info
		ec, user := dbmgr.Center_GetUserInfo(req.Name, func(u *dbmgr.UserInfo) {
			u.IP = sess.GetIP() // creation ip
		})
		if ec != Err.OK {
			return ec
		}

		// currently, our demo just uses game1
		gsid := int32(1)

		// login player: 通知到 GS
		b := sess.LoginPlayer(gsid, &msg.GW_UserOnline{
			Sid:      sess.GetId(),
			UserId:   user.UserId,
			UserName: user.Name,
			LoginIP:  sess.GetIP(),
		})
		if b {
			return Err.OK
		} else {
			return Err.Login_Failed
		}
	}()

	// send result
	sess.SendMsg(&msg.GW_Login_R{
		ErrorCode: ec,
	})
}
